package com.shine.app.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.shine.app.R;
import com.shine.app.bean.CourseImageBean;

public class GalleryAdapter extends BaseAdapter {
	private CourseImageBean[] images;
	private LayoutInflater inflater;
	private Context context;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	public GalleryAdapter(Context con, CourseImageBean[] imageView,
			ImageLoader loader) {
		this.context = con;
		this.images = imageView;
		inflater = LayoutInflater.from(context);
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		this.imageLoader = loader;
	}

	@Override
	public int getCount() {
		return images.length;
	}

	@Override
	public Object getItem(int position) {
		return images[position];
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.gallery_item, null);
			holder = new ViewHolder();
			holder.progressBar = (ProgressBar) convertView
					.findViewById(R.id.progressBar);
			holder.imageView = (ImageView) convertView
					.findViewById(R.id.imageView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		String imageUrl = images[position].getUrl();
		imageLoader.displayImage(imageUrl, holder.imageView, options,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingStarted(String imageUri, View view) {
						holder.progressBar.setVisibility(View.VISIBLE);
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						holder.progressBar.setVisibility(View.GONE);
					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						holder.progressBar.setVisibility(View.GONE);
					}
				}, null);
		return convertView;
	}

	static class ViewHolder {
		private ProgressBar progressBar;
		private ImageView imageView;
	}
}
